package com.bpzj.mybatis.typehandler;

import com.mysql.cj.MysqlType;
import com.mysql.cj.jdbc.result.ResultSetImpl;
import com.mysql.cj.jdbc.result.ResultSetMetaData;
import com.mysql.cj.result.Field;
import org.apache.ibatis.type.*;

import java.sql.*;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@MappedTypes(List.class)
@MappedJdbcTypes(JdbcType.VARCHAR)
public class ListTypeHandler extends BaseTypeHandler<List> {

  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, List parameter, JdbcType jdbcType) throws SQLException {
    ps.setString(i, (String) parameter.get(0));
  }

  @Override
  public List getNullableResult(ResultSet rs, String columnName) throws SQLException {
    List<String> list = new ArrayList<>();
    Field[] fields = ((ResultSetMetaData) rs.getMetaData()).getFields();
    for (Field field : fields) {
      String name = field.getName();
      MysqlType mysqlType = field.getMysqlType();
      String string;
      if (mysqlType == MysqlType.DATETIME || mysqlType == MysqlType.TIME || mysqlType == MysqlType.TIMESTAMP) {
        int index = rs.findColumn(name);
        Timestamp timestamp = rs.getTimestamp(index);
        if (timestamp == null) {
          string = "";
        } else {
          LocalDateTime localDateTime = timestamp.toLocalDateTime();
          string = localDateTime.toString();
        }
      } else {
        string = rs.getString(name);
      }
      list.add(string);
    }
    return list;
  }

  @Override
  public List getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    String s = rs.getString(columnIndex);
    List<String> list = new ArrayList<>();
    list.add(s);
    return list;
  }

  @Override
  public List getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    String s = cs.getString(columnIndex);
    List<String> list = new ArrayList<>();
    list.add(s);
    return list;
  }

}